<template>
  <div class="callback-container"></div>
</template>
<script>
import {
  getTripartiteData,
  getTenantByUid,
  getPermissionByUserIdAndTenant,
  tokenRefresh,
} from "@/api/auth";
import { saveData, clearStorageData, getLoginData } from "@/tools";
import { flatTreeData, getNodeByKey } from "@/utils";
export default {
  data() {
    return {
      loading: null,
      user_token: null,
    };
  },
  mounted() {
    console.log(this.$route);
    clearStorageData();
    if (this.isParamValidity()) {
      let { query } = this.$route;
      this.loading = this.$loading({
        lock: true,
        text: "权限认证中...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      if (query?.back) {
        this.tokenRefresh(query?.uid ?? "");
      } else {
        this.getLoginData();
      }
    } else {
      this.$message.error("很抱歉，权限认证失败~");
    }
    //
  },
  methods: {
    //判断参数是否合法
    isParamValidity() {
      let { query } = this.$route;
      if (query?.user_token || query?.back) {
        this.user_token = query.user_token;
        return true;
      } else {
        return false;
      }
    },

    //刷新token
    tokenRefresh(id) {
      return new Promise((resolve, reject) => {
        tokenRefresh({ userId: id })
          .then((res) => {
            let { data } = res;
            let { userInfo } = data;
            this.saveLoginData(data);
            this.getTenantData(userInfo);
            resolve();
          })
          .catch((_) => {
            this.loading = false;
            this.$message.error("很抱歉，权限认证失败~");
            reject();
          })
          .finally((_) => {});
      });
    },

    //获取登录信息
    getLoginData() {
      let { user_token } = this;
      return new Promise((resolve, reject) => {
        getTripartiteData({
          token: user_token,
        })
          .then((res) => {
            let { data } = res;
            let { userInfo } = data;
            this.saveLoginData(data);
            this.getTenantData(userInfo ?? {});
            resolve();
          })
          .catch((_) => {
            // this.$router.push({
            //   path: "/login",
            //   replace: true,
            // });
            this.errorTip();
            reject();
          })
          .finally((_) => {
            this.loading && this.loading.close();
          });
      });
    },

    //查询租户列表
    getTenantData(userInfo = {}) {
      let { uid } = userInfo;
      return new Promise((resolve, reject) => {
        getTenantByUid({ userId: uid })
          .then((res) => {
            let { data } = res;
            let source = data?.result || [];
            let organization = flatTreeData(source, "child").find(
              (v) => !v.child || v.child.length == 0
            );
            saveData("TENANT_DATA", source);
            saveData("TENANT", organization);
            saveData("ORGANIZATION", organization);
            this.getPermissionData(userInfo);
            resolve();
          })
          .catch((_) => {
            this.errorTip();
            reject();
          });
      });
    },

    //是否已经登陆过
    isLogined() {
      let flag = localStorage.getItem("CALLBACKPAGE");
      let loginData = localStorage.getItem("LOGIN_DATA");
      let userInfo = localStorage.getItem("USER_INFO");
      if (flag && flag == 1) {
        if (loginData && userInfo) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },

    //查询权限资源
    getPermissionData(userInfo = {}) {
      let { query } = this.$route;
      return new Promise((resolve, reject) => {
        let { tenantCode } = getLoginData();
        let { uid, isLeader, id } = userInfo;
        getPermissionByUserIdAndTenant({ userId: uid, tenantCode })
          .then((res) => {
            let { data } = res;
            let source = data?.result || [];
            //权限数据
            saveData("PERMISIONS_DATA", source);
            //配置中心
            let configCenter = source.find((v) => v.menuType == 1);
            saveData("CONFIG_CENTER", configCenter?.child ?? []);
            //系统
            let { child } = source.find((v) => v.menuType == 0);
            let system = child?.[0] ?? {};
            saveData("SYSTEM", { ...system, $$INIT: false });
            //左侧菜单
            let serviceSource = system?.childs?.[0]?.childs ?? [];
            saveData("SERVICE_SOURCE", serviceSource);
            //第一个菜单路由
            let currentMenu = flatTreeData(serviceSource, "childs").find(
              (v) => !v.childs || v.childs.length == 0
            );
            saveData("CURRENT_MENU", currentMenu);
            if (isLeader == 1 && !query?.back) {
              let { origin } = window.location;
              let { VUE_APP_CURRENTMODE } = process.env;
              let domainPath = "";
              if (VUE_APP_CURRENTMODE == "build") {
                domainPath = origin;
              } else {
                domainPath = `http://219.139.133.163:70`;
              }
              let targetPath = this.getTargetPath();
              //领导-跳转到梁厂大屏
              window.location.href = `${domainPath}${targetPath}/?source=jzb&uid=${uid}&id=${id}&sign=${new Date().getTime()}`;
            } else {
              //普通员工
              this.$router.push({
                path: "/serviceView",
                replace: true,
              });
            }

            resolve();
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {
            this.loading && this.loading.close();
          });
      });
    },
    //
    getTargetPath() {
      let { path } = this.$route;
      let target = path.split("/callback")?.[1] ?? "";
      switch (target) {
        //项目部大屏
        case "/department":
          return "/department-visual";

        //
        default:
          return "/beam-control";
      }
    },

    //存储相关信息
    saveLoginData(data = {}) {
      let { userInfo, access_token } = data;
      saveData("LOGIN_DATA", data);
      saveData("CALLBACKPAGE", 1);
      saveData("USER_INFO", userInfo ?? {});
      saveData("ACCESS_TOKEN", access_token ?? "");
      saveData("PAGE_REFRESH", 1);
    },

    errorTip() {
      clearStorageData();
      this.loading && this.loading.close();
      this.$message.error("很抱歉，权限认证失败~");
    },
  },
};
</script>
<style lang="less" scoped></style>
